package com.pks.datacenter.utils;

import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import com.pks.datacenter.job.QuartzJob;

public class QuartzManager {
	private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
	private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";

	/**
	 * 添加一个定时任务，使用默认的任务组名，触发器名，触发器组名
	 * @param jobName 任务名
	 * @param jobClass 任务
	 * @param time 时间设置，参考quartz说明文档
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void addJob(String jobName, Class jobClass, String time,String param) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();
			jobDetail.getJobDataMap().put("param", param);
			// 基于表达式构建触发器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
			// CronTrigger表达式触发器 继承于Trigger
			// TriggerBuilder 用于构建触发器实例
			CronTrigger trigger = TriggerBuilder.newTrigger()
					.withIdentity(jobName, TRIGGER_GROUP_NAME).withSchedule(cronScheduleBuilder).build();

			sched.scheduleJob(jobDetail, trigger);
			// 启动
			if (!sched.isShutdown()) {
				sched.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 修改某个任务的执行时间
	 * 
	 * @param name
	 * @param time
	 */
	public static boolean modifyJob(String name, String time)
			throws SchedulerException {
		Scheduler sched = gSchedulerFactory.getScheduler();
		Date date = null;
		TriggerKey triggerKey = new TriggerKey(name, TRIGGER_GROUP_NAME);
		CronTrigger cronTrigger = (CronTrigger) sched.getTrigger(triggerKey);
		String oldTime = cronTrigger.getCronExpression();
		if (!oldTime.equalsIgnoreCase(time)) {
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
			CronTrigger trigger = TriggerBuilder.newTrigger()
					.withIdentity(name, TRIGGER_GROUP_NAME).withSchedule(cronScheduleBuilder).build();
			date = sched.rescheduleJob(triggerKey, trigger);
		}
		return date != null;
	}
	
	  /**
     * 获取Job信息
     * @param name
     */
    public static String getJobInfo(String name) throws SchedulerException {
    	Scheduler sched = gSchedulerFactory.getScheduler();
        TriggerKey triggerKey = new TriggerKey(name, TRIGGER_GROUP_NAME);
        CronTrigger cronTrigger = (CronTrigger) sched.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
        		sched.getTriggerState(triggerKey).name());
    }

    /**
     * 暂停所有任务
     */
    public static void pauseAllJob() throws SchedulerException {
    	Scheduler sched = gSchedulerFactory.getScheduler();
    	sched.pauseAll();
    }

    /**
     * 暂停某个任务
     * 
     * @param name
     */
    public static void pauseJob(String name) throws SchedulerException {
    	Scheduler sched = gSchedulerFactory.getScheduler();
        JobKey jobKey = new JobKey(name, JOB_GROUP_NAME);
        JobDetail jobDetail = sched.getJobDetail(jobKey);
        if (jobDetail == null) return;
        sched.pauseJob(jobKey);
    }

    /**
     * 恢复所有任务
     * @throws SchedulerException
     */
    public static void resumeAllJob() throws SchedulerException {
    	Scheduler sched = gSchedulerFactory.getScheduler();
        sched.resumeAll();
    }

    /**
     * 恢复某个任务
     * 
     * @param name
     */
    public static void resumeJob(String name) throws SchedulerException {
    	Scheduler sched = gSchedulerFactory.getScheduler();
        JobKey jobKey = new JobKey(name, JOB_GROUP_NAME);
        JobDetail jobDetail = sched.getJobDetail(jobKey);
        if (jobDetail == null) return;
        sched.resumeJob(jobKey);
    }

    /**
     * 删除某个任务
     * 
     * @param name
     */
    public static void deleteJob(String name) throws SchedulerException {
    	Scheduler sched = gSchedulerFactory.getScheduler();
        JobKey jobKey = new JobKey(name, JOB_GROUP_NAME);
        JobDetail jobDetail = sched.getJobDetail(jobKey);
        if (jobDetail == null) return;
        sched.deleteJob(jobKey);
    }
    
    public static void main(String[] args) throws Exception {
    	addJob("job_123", QuartzJob.class, "0/2 * * * * ? *","测试111");
    	Thread.sleep(5000L);
    	modifyJob("job_123","0/1 * * * * ? *");
    	Thread.sleep(50000L);
    	deleteJob("job_123");
	}

}
